﻿using Azure.Core;
using Furion.DataEncryption;
using Furion.FriendlyException;
using Furion.Localization;
using ST.Torch.WebApi.Application;
using ST.Torch.WebApi.Application.System.Services;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using StackExchange.Profiling.Internal;
using System.Security.Claims;

namespace ST.Torch.WebApi.Web.Entry.Controllers;

//[AllowAnonymous]
public class HomeController : Controller
{
    private readonly ISystemService _systemService;
    private readonly ISYSUserService _SYSUserService;
    private readonly IUIDService _UIDService;
    

    public HomeController(ISystemService systemService, ISYSUserService SYSUserService, IUIDService UIDService)
    {
        _systemService = systemService;
        _SYSUserService = SYSUserService;
        _UIDService = UIDService;   
    }
    [AppAuthorize]
    public IActionResult Index()
    {
        ViewBag.Description = _systemService.GetDescription();
        return View("PearIndex");

        //return View();
    }
    public IActionResult Login()
    {
        return View();

    }
    /// <summary>
    /// 登出系统
    /// </summary>
    [AppAuthorize]
    public new async Task<RedirectToActionResult> SignOut()
    {
        await _UIDService.CleanCache();
        await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        //清除信息缓存  
        return RedirectToAction("Login");
    }
    public  async Task<dynamic> LoginSubmit([FromForm]string Account, [FromForm]string Password)
    {
        try
        {
            string ErrorMsg = "";
            var userInfo =await  _SYSUserService.SingleAsync(u => u.Account == Account);
            if (userInfo == null)
            {
                ErrorMsg=($" {L.Text["账号不存在"]}");
                return new { code = 500, Errors = ErrorMsg };

            }
            else
            {
                if (userInfo.Password != userInfo.GetPassEncryption(Password))
                {
                    ErrorMsg=($" {L.Text["密码错误"]}");
                    return new { code = 500, Errors = ErrorMsg };

                }
                // 生成 token
                string accessToken = JWTEncryption.Encrypt(new Dictionary<string, object>
                {
                       { "UserId",userInfo.Id }

                });
                
                //创建用户身份标识
                var claimsIdentity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                claimsIdentity.AddClaims(new List<Claim>()
                    {
                        new Claim("UserId", userInfo.Id.ToString()),

                    });
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));

                //return RedirectToAction("Index", "Home");
                return new { code=200, UserId = userInfo.Id, accessToken = accessToken };


            }


        }
        catch (Exception e)
        {
            //throw Oops.Oh($"" + e.Message);
            return new { code = 500, Errors = e.Message };

        }
        //return View();

    }
	/// <summary>
	/// 国际化配置
	/// </summary>
	/// <param name="Lang"></param>
	/// <param name="returnUrl"></param>
	public IActionResult LanguageSelect(string Lang, string returnUrl)
	{
		L.SetCulture(Lang);
        if (string.IsNullOrEmpty(returnUrl))
        {
            returnUrl = "/";

		}
		return Redirect(returnUrl);
	}
	public IActionResult PearIndex()
    {
        ViewBag.Description = _systemService.GetDescription();

        return View();
    }
    
    [AppAuthorize]
    public IActionResult PearConfigyml()
    {
        return View();
    }

    [AppAuthorize]
    public IActionResult PearConfig()
    {
        //ViewBag.Description = _systemService.GetDescription();
        //"data": "/PearAdmin/admin/data/menu.json",
        //"data": "/api/System/GetCurrUserMenus",
        //"select": "10",
        //"select": "08dcb688 -e726-4b38-807c-5e15ae050e87",

        string Config = """
            {
            	"logo": {
            		"title": "Pear Admin",
            		"image": "/PearAdmin/admin/images/logo.png"
            	},
            	"menu": {		
                    "data": "/api/System/GetCurrUserMenus",
            		"method": "GET",
            		"accordion": true,
            		"collapse": false,
            		"control": false,
            		"controlWidth": 500,
                    "select": "HomePage",
            		"async": true
            	},
            	"tab": {
            		"enable": true,
            		"keepState": true,
            		"session": true,
            		"preload": false,
            		"max": "30",
            		"index": {
            			"id": "HomePage",
            			"href": "/Home/Console",
            			"title": "首页"
            		}
            	},
            	"theme": {
            		"defaultColor": "2",
            		"defaultMenu": "dark-theme",
            		"defaultHeader": "light-theme",
            		"allowCustom": true,
            		"banner": false
            	},
            	"colors": [
            		{
            			"id": "1",
            			"color": "#2d8cf0",
            			"second": "#ecf5ff"
            		},
            		{
            			"id": "2",
            			"color": "#36b368",
            			"second": "#f0f9eb"
            		},
            		{
            			"id": "3",
            			"color": "#f6ad55",
            			"second": "#fdf6ec"
            		},
            		{
            			"id": "4",
            			"color": "#f56c6c",
            			"second": "#fef0f0"
            		},
            		{
            			"id": "5",
            			"color": "#3963bc",
            			"second": "#ecf5ff"
            		}
            	],
            	"other": {
            		"keepLoad": "1200",
            		"autoHead": false,
            		"footer": false
            	},
            	"header": {
            		"message": "/PearAdmin/admin/data/message.json"
            	}
            }
            """;
        return Content(Config);
    }


    public IActionResult Error403()
    {
        return View();
    }

    /// <summary>
    /// 首页
    /// </summary>
    /// <returns></returns>
    public IActionResult Console()
    {
        return View();
    }

    /// <summary>
    /// 首页
    /// </summary>
    /// <returns></returns>
    public IActionResult Torch()
    {
        return View();
    }

}
